package com.example.qsmx;


import com.example.qsmx.Util.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;


@WebServlet("/user-enroll")
@MultipartConfig
public class UserEnroll extends HttpServlet {

    public java.sql.Date stringTSql(String utilData) throws ParseException {
        // 将用户没有输入的东西给予固定值
        // 如果用户没有填写这个属性，那就将这个值设定为 2004-09-09
        // 但是也有可能输入的是 " " 不能够使用，所以还要确保不为空
        if (utilData == null || utilData.trim().isEmpty()) {
            utilData = "2004-09-09";
        }
        // 我们有一个String类型的日期

        // 创建一个SimpleDateFormat对象，并设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 使用SimpleDateFormat对象解析String类型的日期
        Date utilDate = sdf.parse(utilData);

        // 将java.util.Date转换为java.sql.Date
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        // 将数据库的 date 返回
        return sqlDate;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端用户输入的所有数据
        String userName = req.getParameter("userName");
        String userEmail = req.getParameter("userEmail");
        String userTel = req.getParameter("userTel");
        String userAccount = req.getParameter("userAccount");
        String userPassword = req.getParameter("userPassword");
        String userRpassword = req.getParameter("userRpassword");
        String userSex = req.getParameter("sex");
        String userBirthday = req.getParameter("userBirthday");
        Part avatar = req.getPart("avatar");
        String userIntroduce = req.getParameter("introduce");

        // 判断名称长度是否大于 10， 如果大于 10 则返回错误
        if (userName.length() > 10) {
            System.out.println(" 在这里输出，输入的用户名长度太长了，请使用长度小于 10 的用户名");
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>" +
                    "alert('输入的用户名长度太长了，请使用长度小于 10 的用户名，请重新输入！');" +
                    "window.location.href='enroll.jsp';</script>')");
            // 当用户名输入过长的话，停止下面的所有步骤
            return;
        }

        // 判断两次的密码输入是否相同，相同才能进行下一步，不相同则返回两次密码输入错误
        if (!userPassword.equals(userRpassword)) {
            System.out.println(" 在这里输出 两次密码输入错误 ");
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("<script language='javascript'>" +
                    "alert('两次密码输入错误，请重新输入！');" +
                    "window.location.href='enroll.jsp';</script>')");
            // 当两次密码输入不同时，停止下面的所有步骤
            return;
        }

        // 将 String 类型转为 sql.Date 类型
        java.sql.Date sqlUserBirthday;
        try {
            sqlUserBirthday = stringTSql(userBirthday);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 自动添加注册时间
        LocalDate createUserDate = LocalDate.now();
        java.sql.Date sqlCreateUserDate;
        try {
            sqlCreateUserDate = stringTSql(createUserDate.toString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 连接数据库
        Connection connection;
        connection = MyDBUtil.getConnection();

        // 要上传到哪里
        //String uploadPath = Paths.get(System.getProperty("user.home") + "/Desktop/blog/src/main/webapp/uploads").toAbsolutePath().toString();
        String uploadPath = getServletContext().getRealPath("/") + "userAvatar";

        // 处理文件上传 - start
        String avatarFileName = null;

        // 判断用户有没有上传封面图
        if (avatar != null && avatar.getSize() > 0) {
            String fileName = "user" + userAccount;

            // 检查 userAvatar 文件夹是否存在，如果不存在，自动创建
            Path uploadsPath = Paths.get(uploadPath);
            if (!Files.exists(uploadsPath)) {
                Files.createDirectories(uploadsPath);
            }

            // 把头像存储在对应文件下
            File uploadedFile = new File(uploadPath, fileName);
            avatar.write(uploadedFile.getAbsolutePath());
            avatarFileName = "userAvatar/" + fileName + ".png";
        } else {
            avatarFileName = "userAvatar/DefaultAvatar.png";
        }

        // 在数据库中添加数据库对应的内容
        String addSql = "INSERT INTO qsmxusers (userName, userEmail, userTel, userAccount, userPassword, userSex, userBirthday, userAvatar, userIntroduce, userEnrollTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement preparedStatement;
        try {
            preparedStatement = connection.prepareStatement(addSql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //按照 sql 语句添加对应的内容
        try {
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, userEmail);
            preparedStatement.setString(3, userTel);
            preparedStatement.setString(4, userAccount);
            preparedStatement.setString(5, userPassword);
            preparedStatement.setString(6, userSex);
            preparedStatement.setDate(7, sqlUserBirthday);
            preparedStatement.setString(8, avatarFileName);
            preparedStatement.setString(9, userIntroduce);
            preparedStatement.setDate(10, sqlCreateUserDate);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        int rowsInserted;
        try {
            rowsInserted = preparedStatement.executeUpdate();
        } catch (SQLIntegrityConstraintViolationException e) {
            // 处理违反唯一约束的情况
            // 判断对应的数据是否已经被添加
            System.out.println("账号已存在。=====================");
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
       /* try {
            preparedStatement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }*/
        if (rowsInserted > 0) {
            System.out.println("数据添加成功！");
        }

        // 跳转到 main-interface
        req.getRequestDispatcher("main-interface.jap").forward(req, resp);

    }
}
